package com.chris.module.webclient.config;

import com.chris.module.webclient.dto.ConfigDTO;
import com.chris.module.webclient.core.WebClientDataSouce;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(WebClientProperties.class)
public class WebClientConfiguration {

    @Autowired
    WebClientProperties webClientProperties;


    @Bean
    @ConditionalOnProperty(prefix = "webclientunit", name = "enable", havingValue = "true")
    public WebClientDataSouce webClientDataSouce() {
        WebClientDataSouce wcd = new WebClientDataSouce();
        Logger logger = LoggerFactory.getLogger("WebClientUnit");
        for (ConfigDTO config :
                webClientProperties.getConfigs()) {
            wcd.addDataSource(config);
            logger.info("注入: " + config.getName() + " 源");
        }
        return wcd;
    }



    /*
    @Bean
    @ConditionalOnProperty(prefix = "webclientunit", name = "enable", havingValue = "true")
    public List<ConfigDTO> webClientAutoConfig(ConfigurableApplicationContext app) {
        Logger logger = LoggerFactory.getLogger("WebClientUnit");
        int i = 0;
        for (ConfigDTO config :
                webClientProperties.getConfigs()) {

            // 获取bean工厂并转换为DefaultListableBeanFactory
            DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) app.getBeanFactory();

            // 通过BeanDefinitionBuilder创建bean定义
            GenericBeanDefinition beandefinition = new GenericBeanDefinition();

            beandefinition.setBeanClass(WebClientUnit.class);
            // 设置属性
            if (i == 0)
                beandefinition.setPrimary(true);

            // userService,此属性引用已经定义的bean:userService,这里userService已经被spring容器管理了.
            //beanDefinitionBuilder.addPropertyReference("testService", "testService");

            // 注册bean
            defaultListableBeanFactory.registerBeanDefinition(config.getName(), beandefinition);

            //defaultListableBeanFactory.registerSingleton();

            logger.info("注入: " + config.getName() + " 源");
            i++;

            //app.refresh();
        }

        return webClientProperties.getConfigs();
    }

     */
}
